const {
  app,
  BrowserWindow,
  ipcMain,
  Tray,
  Menu,
  dialog,
} = require("electron/main");
const { join } = require("node:path");

// 关闭electron警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
// 初始全局变量
let mainWin = new Object();
let tray = new Object();
/**
 * 创建实例
 */
const createWindow = () => {
  mainWin = new BrowserWindow({
    width: 1024,
    height: 768,
    title: "AiS",
    fullscreenable: false,
    maximizable: false, //禁止最大化
    resizable: false, //禁止调整大小
    autoHideMenuBar: true, //自动隐藏菜单栏
    skipTaskbar: true, // 隐藏任务栏图标

    icon: join(__dirname, "../public/logo.ico"),
    webPreferences: {
      preload: join(__dirname, "./preload.js"),
      nativeWindowOpen: false, // 禁用原生窗口打开功能
    },
  });
  if (process.env.VITE_DEV_SERVER_URL) {
    mainWin.loadURL(process.env.VITE_DEV_SERVER_URL);
  } else {
    mainWin.loadFile(join(__dirname, "../dist/index.html"));
  }
};
/**
 * 加载数据
 */
app.whenReady().then(() => {
  tray = new Tray(join(__dirname, "../public/logo.ico"));
  tray.setToolTip("AiS");

  ipcMain.handle("ping", () => "pong");
  createWindow();

  // 设置开机自启
  // app.setLoginItemSettings({
  //   openAtLogin: true,
  //   path: process.execPath,
  // });
  // 托盘右键菜单
  const menu = Menu.buildFromTemplate([
    {
      label: "退出AIS",
      click: () => app.quit(),
    },
  ]);
  tray.setContextMenu(menu);

  // 监听托盘双击事件
  tray.on("double-click", () => {
    if (mainWin.isVisible()) {
      mainWin.hide();
    } else {
      mainWin.show();
    }
  });
  // 只能运行一个程序
  const shouldQuit = app.requestSingleInstanceLock();
  if (!shouldQuit) app.quit();

  // 监听窗口关闭事件
  mainWin.on("close", (event) => {
    event.preventDefault();
    dialog
      .showMessageBox(mainWin, {
        type: "warning",
        buttons: ["取消", "确定关闭"],
        defaultId: 1,
        title: "确认",
        message: "确定要关闭窗口吗？",
        detail: "关闭窗口将导致未保存的数据丢失。",
      })
      .then((res) => {
        if (res.response === 1) {
          // 移除事件监听，避免递归调用
          mainWin.removeAllListeners("close");
          mainWin.close();
        }
      });
  });
});
